package com.iweb;

import com.iweb.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

public class HelloWorldApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext context) {

        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        ac.register(AppConfig.class);
        ac.refresh();

        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = context.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");

        // 配置请求乱码
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        FilterRegistration.Dynamic filterRegistration = context.addFilter("encodingFilter", encodingFilter);
        // 第一个参数为null，则是缺省的REQUEST模式
        // 第二个参数false表明在代码设置的filter先于web.xml中设置的filter，true则是先web.xml定义的filter后代码设置的。
        filterRegistration.addMappingForUrlPatterns(null, false, "/*");

    }


}
